package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.dto.AccessTokenResultDto;
import com.zzyl.dto.Code2sessionDtoResult;
import com.zzyl.dto.Code2sessionResultDto;
import com.zzyl.dto.PhoneNumberResultDto;
import com.zzyl.service.WxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class WxServiceImpl implements WxService {
    @Override
    public Code2sessionResultDto  code2session(String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, Object> params = new HashMap<>();
        params.put("appid", "wx534a8787a19c4d64");
        params.put("secret", "414bef1e763c0805a795903ac877a00e");
        params.put("js_code", code);
        params.put("grant_type", "authorization_code");
        String res = HttpUtil.get(url, params);
        log.info("code2session result:{}", res);
        Code2sessionResultDto Code2sessionResultDto = JSONUtil.toBean(res, Code2sessionResultDto.class);
        return Code2sessionResultDto;
    }

    @Override
    public AccessTokenResultDto accessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        Map<String, Object> params = new HashMap<>();
        params.put("appid", "wx534a8787a19c4d64");
        params.put("secret", "414bef1e763c0805a795903ac877a00e");
        params.put("grant_type", "client_credential");
        String res = HttpUtil.get(url, params);
        log.info("accessToken result:{}", res);
        AccessTokenResultDto accessTokenResultDto = JSONUtil.toBean(res, AccessTokenResultDto.class);
        return accessTokenResultDto;
    }

    @Override
    public PhoneNumberResultDto getPhoneNumber(String token, String phoneCode) {
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+token;
        Map<String, Object> params = new HashMap<>();
        params.put("code",phoneCode);
        String json =JSONUtil.toJsonStr(params);
        String response = HttpUtil.post(url, json);
        log.info("getPhoneNumber result:{}", response);
        return  JSONUtil.toBean(response, PhoneNumberResultDto.class);
    }
}
